package it.saga.pes.opencms;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
 
public class OpencmsFilter implements Filter {
 
	private static String OPENCMS_SERVICES_URL="/opencms/system/modules/it.saga.pes.frontoffice.servizi.struts2.serviziostep/services";
	private static String OPENCMS_ELEMENTS_URL="/opencms/system/modules/it.saga.pes.frontoffice.servizi.struts2.serviziostep/elements";
	
	private static Logger log = Logger.getLogger(OpencmsFilter.class);
	
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException { 
        HttpServletRequest request = (HttpServletRequest) req;      
        HttpServletResponse response = (HttpServletResponse) res;
        String page = request.getServletPath();
        log.debug("page:"+page);
        if(page.startsWith(OPENCMS_SERVICES_URL)){
        	String redirect = page.replaceFirst(OPENCMS_SERVICES_URL, "");
        	log.debug("redirect to "+redirect);
        	request.getRequestDispatcher(redirect).forward(request, response);
        	return;
        } else if(page.startsWith(OPENCMS_ELEMENTS_URL)){
        	String redirect = page.replaceFirst(OPENCMS_ELEMENTS_URL, "");
        	log.debug("redirect to "+redirect);
        	request.getRequestDispatcher(redirect).forward(request, response);
        	return;
        } else{
        	log.debug("chain:"+page);
        	chain.doFilter(req, res);
        }
    }
    
    public void init(FilterConfig config) throws ServletException {
        String testParam = config.getServletContext().getInitParameter("portal");
        log.debug("Deploy Portal: " + testParam);
    }
    
    public void destroy() {
        //add code to release any resource
    }
}